<template>
  <div class="data">
    <div class="total">
      <div class="time" @click="monthToggle">
        <span>{{ currentMonth }}</span>
        <van-icon name="notes-o" />
      </div>
      <div class="title">共支出</div>
      <div class="expense">¥{{ total_expense || 0 }}</div>
      <div class="income">共收入¥{{ total_income || 0 }}</div>
    </div>
    <div class="structure">
      <div class="head">
        <span class="title">收支构成</span>
        <div class="tab">
          <span
            @click="changeTotalType('expense')"
            class="expense"
            :class="{ active: totalType == 'expense' }"
            >支出</span
          >
          <span
            @click="changeTotalType('income')"
            class="income"
            :class="{ active: totalType == 'income' }"
            >收入</span
          >
        </div>
      </div>
      <div class="content">
        <div
          class="item"
          v-for="item in totalType == 'expense' ? expense_data : income_data"
          :key="item.type_id"
        >
          <div class="left">
            <div class="type">
              <span
                :class="{
                  expense: totalType == 'expense',
                  income: totalType == 'income'
                }"
              >
                <i
                  class="iconfont"
                  :class="item.type_id ? typeMap[item.type_id].icon : 0"
                />
              </span>
              <span>{{ item.type_name }}</span>
            </div>
            <div class="progress">
              {{
                Number(
                  (item.number /
                    Number(
                      totalType == "expense" ? total_expense : total_income
                    )) *
                    100
                ).toFixed(2)
              }}%
            </div>
          </div>
          <div class="right">
            <div class="percent">
              <van-progress
                :percentage="
                  Number(
                    (item.number /
                      Number(
                        totalType == 'expense' ? total_expense : total_income
                      )) *
                      100
                  )
                "
                stroke-width="6px"
                :show-pivot="false"
                track-color="#ffffff"
                color="#39be77"
              />
            </div>
            <div class="money">¥{{ Number(item.number).toFixed(2) || 0 }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="proportion">
      <div class="head">
        <span class="title">收支构成</span>
        <div class="tab">
          <span
            @click="changePieType('expense')"
            class="expense"
            :class="{ active: pieType == 'expense' }"
            >支出</span
          >
          <span
            @click="changePieType('income')"
            class="income"
            :class="{ active: pieType == 'income' }"
            >收入</span
          >
        </div>
      </div>
      <canvas id="proportion"></canvas>
    </div>
    <PopMonth ref="popMonthRef" @selectTime="selectMonth" />
  </div>
</template>

<script>
// import * as echarts from "echarts";
import F2 from "@antv/f2/lib/index-all";
import { onMounted, reactive, toRefs, ref } from "vue";
import { typeMap } from "@/utils/typeMap";
import dayjs from "dayjs";
import { get } from "@/utils/request";
import PopMonth from "@/components/PopMonth";
export default {
  name: "Statistics",
  components: {
    PopMonth
  },
  setup() {
    let proportionChart = null;
    const popMonthRef = ref(null);
    const state = reactive({
      typeMap,
      currentMonth: dayjs().format("YYYY-MM"),
      total_expense: 0,
      total_income: 0,
      expense_data: [],
      income_data: [],
      totalType: "expense",
      pieType: "expense"
    });
    onMounted(() => {
      getData();
    });
    const getData = async () => {
      const { data } = await get("/bill/data", {
        date: state.currentMonth
      });

      // 总收支
      state.total_expense = data.total_expense;
      state.total_income = data.total_income;

      // 过滤支出和收入
      state.expense_data = data.total_data
        .filter((item) => item.pay_type == 1)
        .sort((a, b) => b.number - a.number); // 过滤出账单类型为支出的项
      state.income_data = data.total_data
        .filter((item) => item.pay_type == 2)
        .sort((a, b) => b.number - a.number); // 过滤出账单类型为收入的项
      setPieChart();
    };
    // 切换收支构成类型
    const changeTotalType = (type) => {
      state.totalType = type;
    };
    // 切换饼图收支类型
    const changePieType = (type) => {
      state.pieType = type;
      // 重绘饼图
      setPieChart();
    };
    // 绘制饼图方法

    const setPieChart = () => {
      const data =
        state.pieType == "expense" ? state.expense_data : state.income_data;
      console.log(data);
      const total = data.reduce((acc, cur) => {
        return acc + cur.number;
      }, 0);
      data.map((v) => {
        v.type = v.type_name;
        v.money = v.number;
        v.percentage = ((v.number / total) * 100).toFixed(2) + "%";
      });

      const chart = new F2.Chart({
        id: "proportion",
        pixelRatio: window.devicePixelRatio
      });
      chart.source(data);
      chart.coord("polar", {
        transposed: true,
        radius: 0.7,
        innerRadius: 0.7
      });
      chart.axis(false);
      chart.legend(false);
      chart.tooltip(false);
      chart.guide().html({
        position: ["50%", "50%"],
        html:
          '<div style="text-align: center;width:150px;height: 50px;">\n      <p style="font-size: 12px;color: #999;margin: 0" id="title"></p>\n      <p style="font-size: 18px;color: #343434;margin: 0;font-weight: bold;" id="money"></p>\n      </div>'
      });
      chart
        .interval()
        .position("const*money")
        .adjust("stack")
        .color("type", ["#1890FF", "#13C2C2", "#2FC25B", "#FACC14"]);
      chart.pieLabel({
        sidePadding: 30,
        activeShape: true,
        label1: function label1(data) {
          return {
            text: "￥" + data.money,
            fill: "#343434",
            fontWeight: "bold"
          };
        },
        label2: function label2(data) {
          return {
            text: data.type + data.percentage,
            fill: "#999"
          };
        },
        onClick: function onClick(ev) {
          const data = ev.data;
        }
      });
      chart.render();
    };
    // 月份弹窗开关
    const monthToggle = () => {
      popMonthRef.value.toggle();
    };

    const selectMonth = (item) => {
      state.currentMonth = item;
      getData();
    };
    return {
      ...toRefs(state),
      popMonthRef,
      selectMonth,
      monthToggle,
      changeTotalType,
      changePieType
    };
  }
};
</script>

<style lang="less" scoped>
.data {
  min-height: 100%;
  background-color: #f5f5f5;
  .total {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px 0;
    margin-bottom: 10px;
    .time {
      position: relative;
      width: 96px;
      padding: 6px;
      background-color: #f5f5f5;
      color: var(--text-color1);
      border-radius: 4px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      span:nth-of-type(1)::after {
        content: "";
        position: absolute;
        top: 9px;
        bottom: 8px;
        right: 28px;
        width: 1px;
        background-color: rgba(0, 0, 0, 0.5);
      }
      .van-icon-notes-o {
        font-size: 16px;
        color: var(--text-color2);
      }
    }
    .title {
      color: var(--text-color5);
      margin-bottom: 8px;
      font-size: 12px;
      font-weight: 500;
    }
    .expense {
      font-size: 24px;
      color: var(--text-color5);
      font-weight: 600;
      margin-bottom: 16px;
    }
    .income {
      color: var(--text-color2);
      font-weight: 500;
    }
  }
  .structure {
    padding: 0 16px;
    background-color: #fff;
    margin-bottom: 10px;
    .head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      .title {
        font-size: 18px;
        color: var(--text-color1);
      }
      .tab {
        span {
          display: inline-block;
          width: 40px;
          height: 24px;
          background-color: #f5f5f5;
          text-align: center;
          line-height: 24px;
          margin-left: 10px;
          border-radius: 4px;
        }
        .expense {
          &.active {
            background-color: rgba(57, 190, 119, 0.2);
            color: var(--text-color5);
          }
        }
        .income {
          &.active {
            background-color: rgba(236, 190, 37, 0.2);
            color: var(--text-color5);
          }
        }
      }
    }
    .content {
      .item {
        display: flex;
        height: 50px;
        align-items: center;
        .left {
          flex: 5;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-right: 10px;
          .type {
            display: flex;
            align-items: center;
            span:nth-of-type(1) {
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 50%;
              width: 30px;
              height: 30px;
              margin-right: 10px;
              color: #fff;
            }
            .expense {
              background-color: var(--text-color5);
            }
            .income {
              background-color: var(--text-color5);
            }
          }
        }
        .right {
          flex: 8;
          display: flex;
          align-items: center;
          .percent {
            width: 160px;
          }
          .momey {
            width: 100px;
          }
        }
      }
    }
  }
  .proportion {
    background-color: #fff;
    padding: 12px;
    .head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      .title {
        font-size: 18px;
        color: var(--text-color1);
      }
      .tab {
        span {
          display: inline-block;
          width: 40px;
          height: 24px;
          background-color: #f5f5f5;
          text-align: center;
          line-height: 24px;
          margin-left: 10px;
          border-radius: 4px;
        }
        .expense {
          &.active {
            background-color: rgba(57, 190, 119, 0.2);
            color: var(--text-color5);
          }
        }
        .income {
          &.active {
            background-color: rgba(236, 190, 37, 0.2);
            color: var(--text-color5);
          }
        }
      }
    }
    #proportion {
      width: 100%;
      height: 400px;
    }
  }
}
</style>
